package imageDemo;

import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

// 导出图片
public class ExportImageDemo extends Application {
	private StackPane root = new StackPane();
	private Label label;
	
	public static void main(String[] args) {
		launch(args);
	}
	
	@Override
	public void start(Stage stage) {
		
		root.setStyle("-fx-background-color: lightyellow");
		
		Button button = new Button("");
		button.setPrefSize(30, 30);
		button.setStyle("-fx-background-radius: 7; -fx-background-color: orange");
		
		label = new Label("导出图片");
		label.setFont(Font.font(30));
		root.getChildren().addAll(label, button);
		
		Scene scene = new Scene(root, 500, 400);
		stage.setScene(scene);
		stage.show();
		
//		exportImage(button.snapshot(null, null));	// 组件要添加到面板中才能正确导出
	}
	
	// 导出图片
	public void exportImage(WritableImage snapshot){
		// 打开文件选择框
	    FileChooser fc = new FileChooser();
	    fc.setTitle("导出图片");
	    fc.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PNG", "*.png"), 	// 设置导出类型
	        								new FileChooser.ExtensionFilter("JPG", "*.jpg"));
	    // 导出
	    File file = fc.showSaveDialog(null);
	    if(file != null) {
	        try {
	            ImageIO.write(SwingFXUtils.fromFXImage(snapshot, null), "png", file);	// 可导出jpg,png格式
	        } catch(IOException e) {
	            e.printStackTrace();
	        }
	    }
	}
}
